package com.cvit.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;

/**
 * 图片上传
 * */
public class FileUpload {
	public static String uploadFile(MultipartFile file, HttpServletRequest request, String photo) throws IOException {
        String photos = photo;
		String fileName = file.getOriginalFilename();
        String img_path = "Subscribe_mig/";
        DateFormat format = new SimpleDateFormat("yyyyMMddHHmm");//时间格式
        String date=format.format(new Date());//获取当前时间
        String dir = request.getSession().getServletContext().getRealPath("/");//总路径
        String img_name = date+Utils.createRandString();//新生成的图片名（当前时间+六位生成码）
        StringBuilder path = new StringBuilder(dir.substring(0, dir.indexOf("Subscribe")) + img_path);
        StringBuilder delete = new StringBuilder(dir.substring(0, dir.indexOf("Subscribe")));//服务器webapps路径
        String photopath = delete+ photos;//需要删除的路径
        if(photos!=null){
        	deleteServerFile(photopath);
        }
        File tempFile = new File(path.toString(),String.valueOf(img_name+".png"));
        if (!tempFile.getParentFile().exists()) {
            tempFile.getParentFile().mkdir();
        }
        if (!tempFile.exists()) {
            tempFile.createNewFile();
        }
        file.transferTo(tempFile);
        return img_path + img_name+".png";
    }
	
	
	/**
	 * 删除服务器文件
	 * */
	public static boolean deleteServerFile(String imgpath){
		boolean delete_flag = false;
		String b=imgpath.replace("\\","/");
		File file = new File(b);
		if (file.exists() && file.isFile() && file.delete())
	        delete_flag = true;
	       else
	        delete_flag = false;
	    return delete_flag;
	}
	
	/**
	 * 外部接口图片下载到本地
	 * */
	public static String download(String urlString, String filename,HttpServletRequest request) throws Exception {  
        URL url = new URL(urlString);  // 构造URL  
        URLConnection con = url.openConnection(); // 打开连接 
        String img_path = "admissions_mig/";
		String dir = request.getSession().getServletContext().getRealPath("/");//总路径
		StringBuilder path = new StringBuilder(dir.substring(0, dir.indexOf("admissions")) + img_path);
        con.setConnectTimeout(5*1000);  //设置请求超时为5s 
        InputStream is = con.getInputStream();   // 输入流 
        byte[] bs = new byte[1024];  // 1K的数据缓冲  
        int len;  // 读取到的数据长度  
	    File sf=new File(path.toString());// 输出的文件流 
	       if(!sf.exists()){  
	           sf.mkdirs();  
	       }  
	    OutputStream os = new FileOutputStream(sf.getPath()+"\\"+filename+".jpg");  
	       while ((len = is.read(bs)) != -1) {  // 开始读取  
	          os.write(bs, 0, len);  
	       }  
	        os.close();  // 完毕，关闭所有链接  
	        is.close();
	        String image_path = img_path + filename + ".jpg";
	        return image_path;
    	}   
	
	
	/**  
	 * @功能 下载临时素材接口  
	 * @param filePath 文件将要保存的目录  
	 * @param method 请求方法，包括POST和GET  
	 * @param url 请求的路径  
	 * @return  
	 * @throws IOException 
	 */  
	public static File saveUrlAs(String url,String filePath,String method) throws IOException{  
	     //System.out.println("fileName---->"+filePath);  
	     //创建不同的文件夹目录  
	     File file=new File(filePath);  
	     //判断文件夹是否存在  
	     if (!file.exists())  
	    {  
	        //如果文件夹不存在，则创建新的的文件夹  
	         file.mkdirs();  
	    }  
	     FileOutputStream fileOut = null;  
	     HttpURLConnection conn = null;  
	     InputStream inputStream = null;  
	     
	         // 建立链接  
	         URL httpUrl=new URL(url);
	         conn=(HttpURLConnection) httpUrl.openConnection();
	         //以Post方式提交表单，默认get方式  
	         conn.setRequestMethod(method);
	         conn.setDoInput(true);    
	         conn.setDoOutput(true);  
	         // post方式不能使用缓存   
	         conn.setUseCaches(false);  
	         //连接指定的资源   
	         conn.connect();  
	         //获取网络输入流  
	         inputStream=conn.getInputStream();  
	         BufferedInputStream bis = new BufferedInputStream(inputStream);  
	         //判断文件的保存路径后面是否以/结尾  
	         if (!filePath.endsWith("/")) {  
	             filePath += "/";  
	             }  
	         //写入到文件（注意文件保存路径的后面一定要加上文件的名称）  
	         fileOut = new FileOutputStream(filePath+"考生照片.zip");  
	         BufferedOutputStream bos = new BufferedOutputStream(fileOut);  
	         byte[] buf = new byte[4096];  
	         int length = bis.read(buf);  
	         //保存文件  
	         while(length != -1)  
	         {  
	             bos.write(buf, 0, length);  
	             length = bis.read(buf);  
	         }  
	         bos.close();  
	         bis.close();  
	         conn.disconnect();  
	     return file;  
	 }
	
	
	
	/**
     * 下载图片压缩包
     * @param response
     * @throws FileNotFoundException
     * @throws IOException
     */
	public static void downloadFileByOutputStream(HttpServletResponse response,HttpServletRequest request,String zipFilePath,String fileNames)
            throws FileNotFoundException, IOException {
        String realPath = zipFilePath;//获取要下载的文件的绝对路径
        String fileName = fileNames;//获取要下载的文件名
        //设置content-disposition响应头控制浏览器以下载的形式打开文件，中文文件名要使用URLEncoder.encode方法进行编码，否则会出现文件名乱码
        response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(fileName, "UTF-8")+".zip");
        InputStream in = new FileInputStream(realPath+fileName+".zip");//获取文件输入流
        int len = 0;
        byte[] buffer = new byte[1024];
        OutputStream out = response.getOutputStream();
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer,0,len);//将缓冲区的数据输出到客户端浏览器
        }
        in.close();
        out.close();
    }
	
	
	 // 判断文件是否存在
	     public static boolean judeFileExists(String filsePath) {
	    	 File file = new File(filsePath);
	         if (file.exists()==true) {
	             return true;
	         } else {
	             return false;
	         }
	 
	     }
	
	/*public String uploadNews(String tid, String sid) {
		System.out.println("BaseAction-转换后路径"+temp_path);
		String img = null;
		try {
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//子文件夹.
			String img_path = "/tid_"+tid+"/sid_"+sid+"/News/";
			String dir = getServletContext().getRealPath("/");//总路径
			StringBuilder path = new StringBuilder(dir.substring(0, dir.indexOf("app_agent")) + "app_agent_IMG" + img_path);
			if (!Utils.isNull(uoload_Obj)) {
				String img_name = Utils.getUUID() + ".jpg";//图片名字
				Utils.upload(uoload_Obj.getFile(), path.toString(), img_name);
				img= img_path + img_name;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//System.out.println("shop_img:"+shop_img);
		return img;
	}*/
	
}